package com.dingshi.security;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.dingshi.security.api.ApiResult;
import com.dingshi.security.api.ApiReturnResultListener;
import com.dingshi.security.api.NotifyApi;
import com.dingshi.security.db.SettingLoader;
import com.dingshi.security.entity.NotifyEntity;
import com.dingshi.security.entity.Numbers;
import com.dingshi.security.view.LoadDialog;

public class NotifykActivity extends BaseActivity implements OnClickListener {
	LinearLayout  fristButton, secendButton, thridButton;
	ImageButton fristImageButton, secendImageButton, thridImageButton;
	TextView fristTextView, secendTextView, thridTextView;

	ArrayList<Numbers> numbers = new ArrayList<Numbers>();
	private ListView mListView;
	private ArrayList<NotifyEntity> list;

	private TextView btn_recoder;
	private TextView btn_common;
	private TextView btn_contact;
	private Button btn_back;
	private TextView tips_text;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.notifyview);
		btn_back = (Button) findViewById(R.id.btn_back);
		btn_back.setOnClickListener(this);
		initButton();
		tips_text = (TextView)findViewById(R.id.tips_text);
		mListView = (ListView) findViewById(R.id.notifyList);
		mListView.setDividerHeight(0);

		mListView.setPadding(5, 5, 5, 5);
		mListView.setCacheColorHint(Color.WHITE);
		getNotifyList(SettingLoader.getDepartNum(this));
	}


	private static final int ID_LOADING = 2015;

	private void getNotifyList(String departNum) {

		NotifyApi api = new NotifyApi(this);
		api.setReturnResultListener(new ApiReturnResultListener() {

			@Override
			public <T> void onReturnSucceedResult(int requestCode,
					ApiResult<T> apiResult) {
				dismissDialog(ID_LOADING);
				JSONObject jsonEntity = apiResult.getJsonEntity();
				if (jsonEntity != null) {

					try {
						int type = jsonEntity.getInt("t");
						switch (type) {
						case 0:// 对象
							break;
						case 1:// 数组
							JSONArray array = jsonEntity.getJSONArray("d");
							if (array != null) {
								list = new ArrayList<NotifyEntity>();
								NotifyEntity entity = null;
								for (int i = 0; i < array.length(); i++) {
									entity = new NotifyEntity();
									JSONObject opt = (JSONObject) array.opt(i);
									try {
										entity.setNid(opt.getString("i"));

									} catch (Exception e) {
										// TODO: handle exception
									}
									try {
										entity.setContext(opt.getString("c"));

									} catch (Exception e) {
										// TODO: handle exception
									}
									try {
										entity.setSender(opt.getString("p"));

									} catch (Exception e) {
										// TODO: handle exception
									}
									try {
										entity.setTime(opt.getString("d"));

									} catch (Exception e) {
										// TODO: handle exception
									}
									try {
										entity.setTitle(opt.getString("t"));

									} catch (Exception e) {
										// TODO: handle exception
									}
									try {
										entity.setType(opt.getString("s"));
										
									} catch (Exception e) {
										// TODO: handle exception
									}
									list.add(entity);

								}
								refresh("1");
								Log.i("Diary", "size is " + list.size());
							}

							break;
						case -1:// 错误

							break;

						default:
							break;
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}

			@Override
			public <T> void onReturnFailResult(int requestCode,
					ApiResult<T> apiResult) {
				dismissDialog(ID_LOADING);

			}

			@Override
			public <T> void onReturnLoading(int requestCode) {
				showDialog(ID_LOADING);
			}
		});
		api.getNotifyList(0, departNum, this);

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case ID_LOADING:
			LoadDialog dialog = new LoadDialog(this, getResources().getString(R.string.login_loading));
			return dialog;

		default:
			break;
		}
		return super.onCreateDialog(id);
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		super.onPrepareDialog(id, dialog);
	}
	
	public void refresh(String type) {
		ArrayList<NotifyEntity> handleList = handleList(type,list);
		if(handleList!=null&&handleList.size()>0) {
			tips_text.setVisibility(View.GONE);
			mListView.setVisibility(View.VISIBLE);
			ListAdapter adapter = new ListAdapter(this,handleList );
			mListView.setAdapter(adapter);
		}else {
			tips_text.setVisibility(View.VISIBLE);
			mListView.setVisibility(View.GONE);
		}
	}

	private ArrayList<NotifyEntity> handleList(String type, ArrayList<NotifyEntity> list) {
		if(list==null) {
			return null;
		}
		if(type==null) {
			return list;
		}
		ArrayList<NotifyEntity> mList = new ArrayList<NotifyEntity>();
		for(NotifyEntity notify : list) {
			if(type.equals(notify.getType())) {
				mList.add(notify);
			}
		}
		return mList;
	}

	private void initButton() {
		btn_recoder = (TextView) findViewById(R.id.textView1);
		btn_common = (TextView) findViewById(R.id.textView2);
		btn_contact = (TextView) findViewById(R.id.textView3);
		btn_recoder.setOnClickListener(this);
		btn_common.setOnClickListener(this);
		btn_contact.setOnClickListener(this);

	}

	private final class ListAdapter extends BaseAdapter {
		private LayoutInflater inflater;
		private Context context;
		private ArrayList<NotifyEntity> list;

		public ListAdapter(Context context, ArrayList<NotifyEntity> list) {
			this.context = context;
			this.list = list;
			inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final NotifyEntity entity = list.get(position);
			if (entity == null) {
				return null;
			}
			final ViewHolder holder;

			if (convertView == null) {
				convertView = inflater.inflate(R.layout.notify_item, null);

				holder = new ViewHolder();
				holder.headicon = (ImageView) convertView
						.findViewById(R.id.headicon);

				holder.name = (TextView) convertView.findViewById(R.id.name);

				holder.time = (TextView) convertView.findViewById(R.id.time);
				holder.title = (TextView) convertView.findViewById(R.id.title);
				holder.isreaded = (TextView) convertView
						.findViewById(R.id.isreaded);
				convertView.setTag(holder);
				convertView.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent intent = new Intent(NotifykActivity.this,
								NotifyInfoActivity.class);
						intent.putExtra("n", entity.getSender());
						intent.putExtra("t", entity.getTitle());
						intent.putExtra("d", entity.getTime());
						intent.putExtra("c", entity.getContext());
						entity.setIsreaded(true);
						startActivity(intent);
						notifyDataSetChanged();
					}
				});
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			updateData(holder, entity);

			return convertView;
		}

		private void updateData(ViewHolder holder, NotifyEntity entity) {
			holder.headicon.setImageResource(R.drawable.notifyicon);
			holder.name.setText(entity.getSender());
			holder.time.setText(entity.getTime());
			holder.title.setText(entity.getTitle());
			holder.isreaded.setText(entity.isIsreaded() ? "已读" : "未读");
		}

		private String ConvertTime(long createTime) {
			Date date = new Date(createTime);
			SimpleDateFormat format = new SimpleDateFormat("hh:MM:ss");
			return format.format(date);
		}
	}

	static class ViewHolder {
		ImageView headicon;
		TextView title;
		TextView context;
		TextView isreaded;
		TextView name;
		TextView time;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			super.onBackPressed();
			break;
		case R.id.textView1:
			btn_recoder.setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.messageblue, 0, 0, 0);
			btn_common.setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.messageblack, 0, 0, 0);
			btn_contact.setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.messageblack, 0, 0, 0);
			btn_recoder.setTextColor(Color.WHITE);
			btn_common.setTextColor(Color.GRAY);
			btn_contact.setTextColor(Color.GRAY);
			refresh("1");
			break;
		case R.id.textView2:
			btn_recoder.setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.messageblack, 0, 0, 0);
			btn_common.setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.messageblue, 0, 0, 0);
			btn_contact.setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.messageblack, 0, 0, 0);
			btn_recoder.setTextColor(Color.GRAY);
			btn_common.setTextColor(Color.WHITE);
			btn_contact.setTextColor(Color.GRAY);
			refresh("0");
			break;
		case R.id.textView3:
			btn_recoder.setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.messageblack, 0, 0, 0);
			btn_common.setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.messageblack, 0, 0, 0);
			btn_contact.setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.messageblue, 0, 0, 0);
			btn_recoder.setTextColor(Color.GRAY);
			btn_common.setTextColor(Color.GRAY);
			btn_contact.setTextColor(Color.WHITE);
			refresh(null);
			break;
		default:
			break;
		}

	}
}
